use anyhow::{anyhow, Result};
use async_stream::stream;
use async_trait::async_trait;
use bytes::{Buf, BufMut, BytesMut};
use std::{thread, time};
use tauri_plugin_rrai_idns::socket_capnp::{
    map, peer_http_parts, peer_http_request, peer_http_response,
};

use capnp::message::{ReaderOptions, TypedBuilder, TypedReader};

#[tokio::main]
async fn main() -> Result<()> {
    tracing_subscriber::fmt()
        .with_max_level(tracing::Level::DEBUG)
        .init();
    tracing::info!("RRAI 启动...");
    let peer_id = "ssss";
    let host = "ssss";
    let port = "ssss";
    let path = "ssss";
    let query = "ssss";
    let version = "HTTP/1.1";
    let body = b"";

    //
    let mut request_builder = TypedBuilder::<peer_http_request::Owned>::new_default();

    let mut root = request_builder.get_root()?;
    // 设置节点ID
    root.set_peer_id(capnp::text::Reader(peer_id.as_bytes()));

    // headers
    let mut parts_builder = TypedBuilder::<peer_http_parts::Owned>::new_default();
    let mut parts_root = parts_builder.get_root()?;

    //URI
    parts_root.set_uri(capnp::text::Reader(
        format!("{}:{}{}{}", host, port, path, query).as_bytes(),
    ));
    //Method
    parts_root.set_method(capnp::text::Reader("GET".as_bytes()));
    //Version
    parts_root.set_version(capnp::text::Reader(format!("{:?}", version).as_bytes()));
    //headers
    let mut headers_map_builder =
        TypedBuilder::<map::Owned<capnp::text::Owned, capnp::text::Owned>>::new_default();
    parts_root.set_headers(headers_map_builder.get_root_as_reader()?)?;
    //extensions
    let mut extensions_map_builder =
        TypedBuilder::<map::Owned<capnp::text::Owned, capnp::text::Owned>>::new_default();

    parts_root.set_extensions(extensions_map_builder.get_root_as_reader()?)?;
    //head
    root.set_head(parts_builder.get_root_as_reader()?)?;

    //routers
    let mut routers_builder = TypedBuilder::<capnp::text_list::Owned>::new_default();
    root.set_routers(routers_builder.get_root_as_reader()?)?;

    //body
    root.set_body(body);

    let mut buffer = vec![];
    capnp::serialize_packed::write_message(&mut buffer, request_builder.borrow_inner())?;

    tracing::debug!("数据封装完成:{}", buffer.len());

    //
    let reader =
        capnp::serialize_packed::read_message(buffer.to_vec().as_slice(), ReaderOptions::new())
            .map_err(|err| anyhow::anyhow!("解析报文失败:{}", err))?;

    let message_reader = TypedReader::<_, peer_http_request::Owned>::new(reader);
    let rr = message_reader.get().unwrap();
    let head = rr.reborrow().get_head().unwrap();
    let uri = head.reborrow().get_uri()?.to_string()?;
    let peer_id = rr.reborrow().get_peer_id()?.to_string()?;

    tracing::debug!("{}:{}", uri, peer_id);

    Ok(())
}
